//
//  PoisonSlotView.swift
//  Game
//
//  Created by woniu on 2025/9/25.
//

import UIKit

class PoisonSlotView: UIView {
    
    private var titleLabel: UILabel!
    private var slotView: UIView!
    private var isOccupied: Bool = false
    private var poisonWord = ""
    
    var title: String = "" {
        didSet {
            titleLabel.text = title
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        // 槽位
        slotView = UIView()
        slotView.backgroundColor = UIColor.darkGray
        slotView.layer.cornerRadius = 8
        slotView.layer.borderColor = UIColor.gray.cgColor
        slotView.layer.borderWidth = 1
        addSubview(slotView)
        
        // 标题
        titleLabel = UILabel()
        titleLabel.textAlignment = .center
        titleLabel.font = UIFont.systemFont(ofSize: 14)
        titleLabel.textColor = UIColor.lightGray
        titleLabel.text = "未设置"
        addSubview(titleLabel)
        
        // 设置约束
        titleLabel.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        slotView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    // 设置毒药卡片动画效果
    func setPoisonCard(with word: String, from sourceView: UIView, sourceSuperview: UIView) {
        self.poisonWord = word
        // 创建源视图的快照
        let snapshot = sourceView.snapshotView(afterScreenUpdates: false)
        snapshot?.frame = sourceView.convert(sourceView.bounds, to: sourceSuperview)
        sourceSuperview.addSubview(snapshot!)
        
        // 隐藏原始视图
        sourceView.isHidden = true
        
        // 执行动画
        UIView.animate(withDuration: 1.0, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: {
            snapshot?.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)
            let targetFrame = self.slotView.convert(self.slotView.bounds, to: sourceSuperview)
            snapshot?.frame = targetFrame
        }) { _ in
            // 动画完成后显示槽位被占用状态
            self.isOccupied = true
            self.slotView.backgroundColor = UIColor(red: 0.8, green: 0.2, blue: 0.2, alpha: 1.0)
            self.titleLabel.text = "毒药已设置"
            self.titleLabel.textColor = UIColor.white
            
            // 移除快照
            snapshot?.removeFromSuperview()
            sourceView.isHidden = false
        }
    }
    
    // 重置槽位
    func resetSlot() {
        isOccupied = false
        slotView.backgroundColor = UIColor.darkGray
        titleLabel.text = "未设置"
        titleLabel.textColor = UIColor.lightGray
    }
}
